//
//  ReceiveOrderViewController.swift
//  newShaohuoRen
//
//  Created by hujinbiao on 2018/3/22.
//  Copyright © 2018年 hujinbiao. All rights reserved.
//

import UIKit
import MJRefresh
import SwiftProgressHUD

let receiveOrderCell = "ReceiveOrderCell"
let needDealtCell = "NeedDealtCell"
let tableViewCell = "tableViewCell"

class ReceiveOrderViewController: UIViewController {
    
    var toolBarView: UIView?
    
    var MyTableView : UITableView!
    
    var ordersArray = NSMutableArray()
    
    var page = 0
    
    var totalPage = 0
    
    var selIndex = 0
    
    var offDutyButton : UIButton!
    
    var button : UIButton!
    
    var orderTotal : Int!
    
    var unDoneTotal : Int!
    
    var segmentedControll : HMSegmentedControl!
    
    var statusHeight : CGFloat = 20
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if kScreenHeight>=812 {
            statusHeight = 44
        }else {
            statusHeight = 20
        }
        
        self.view.backgroundColor = UIColor.white
        
        //开始接单按钮
        button = UIButton(type: UIButtonType.custom)

        setupToolBar()
        
        initTableView()
        
    }
    
    func initTableView() {
        
        MyTableView = UITableView(frame: CGRect(x: 0, y: 44+40+20+statusHeight, width: kScreenWitdh, height: kScreenHeight-44-40-20))
//        MyTableView.separatorStyle = .none
        MyTableView.dataSource = self
        MyTableView.delegate = self
        MyTableView.rowHeight = UITableViewAutomaticDimension
        MyTableView.estimatedRowHeight = 100
        MyTableView.tableFooterView = UIView()
        MyTableView.register(UINib(nibName: "ReceiveOrderCell", bundle: nil), forCellReuseIdentifier: receiveOrderCell)
        MyTableView.register(UINib(nibName: "NeedDealtCell", bundle: nil), forCellReuseIdentifier: needDealtCell)
        MyTableView.register(UITableViewCell.self, forCellReuseIdentifier: tableViewCell)
        self.view.addSubview(MyTableView)
        
        //上下拉刷新
        refresh()
        MyTableView.mj_header.beginRefreshing()
        
    }
    
    func refresh() {

        // 顶部刷新
        let header = MJRefreshNormalHeader()
        header.setRefreshingTarget(self, refreshingAction: #selector(headerRefresh))
        MyTableView.mj_header = header

        // 底部刷新
        let footer = MJRefreshAutoNormalFooter()
        footer.setRefreshingTarget(self, refreshingAction: #selector(footerRefresh))
        MyTableView.mj_footer = footer

    }

    // 顶部刷新
    @objc fileprivate func headerRefresh(){
         page = 1
        switch selIndex {
        case 0:
            requestOrderListNew(current_page: page)
        case 1:
            requestUnDoneListNew(current_page: page)
        case 2:
            requestAchievement()
        default:
            MyTableView.mj_header.endRefreshing()
        }
    }
    // 底部刷新
    @objc fileprivate func footerRefresh(){
        if page<=totalPage{
            switch selIndex {
            case 0:
                requestOrderListMore(current_page: page)
            case 1:
                requestUnDoneListMore(current_page: page)
            case 2:
                MyTableView.mj_footer.endRefreshing()
            default:
                MyTableView.mj_footer.endRefreshing()
            }
        }else {
            MyTableView.mj_footer.endRefreshing()
        }
    }
    
    
    //接单列表
    func requestOrderListNew(current_page:Int) -> Void {
        
        if !UserTicketModel.sharedInstance.isLogin {
            return
        }
        
        //要加密的数据
        let param = ["command":"orderList","token":UserTicketModel.sharedInstance.token ?? "","uid":UserTicketModel.sharedInstance.uid ?? "","app_name":"shr","lat":"30.2180810000","lng":"120.2206080000","current_page":current_page] as [String : Any]
        let network = NetworkTools.sharedInstance
        network.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"Shipping"], successed: { (resultDict) in
            self.MyTableView.mj_header.endRefreshing()
            
            if let dict = resultDict["data"] as? NSDictionary{
                let jsonString = network.getJSONStringFromDictionary(dictionary: dict)
                
                guard let jsonData = jsonString.data(using: String.Encoding.utf8) else {return}
                do {
                    let objc: HomeItem = try JSONDecoder().decode(HomeItem.self, from: jsonData)
                    self.page = objc.current_page+1
                    self.totalPage = objc.total
                    self.ordersArray.removeAllObjects()
                    let ordersDatas : [OrdersDataItem] = objc.data
                    for order in ordersDatas {
                        self.ordersArray.add(order)
                    }
                    
                    self.MyTableView.reloadData()
                    self.orderTotal = self.totalPage
                    //设置标题
                    self.setSegmentedControl()
                    
                }catch {
                    print(error)
                }
            }

        })
    }
    
    //接单列表
    func requestOrderListMore(current_page:Int) -> Void {
        
        //要加密的数据
        let param = ["command":"orderList","token":UserTicketModel.sharedInstance.token ?? "","uid":UserTicketModel.sharedInstance.uid ?? "","app_name":"shr","lat":UserTicketModel.sharedInstance.lat ?? "","lng":UserTicketModel.sharedInstance.lng ?? "","current_page":current_page] as [String : Any]
        let network = NetworkTools.sharedInstance
        network.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"Shipping"], successed: { (resultDict) in
            self.MyTableView.mj_footer.endRefreshing()
            if let dict = resultDict["data"] as? NSDictionary{
                let jsonString = network.getJSONStringFromDictionary(dictionary: dict)
                
                guard let jsonData = jsonString.data(using: String.Encoding.utf8) else {return}
                do {
                    let objc: HomeItem = try JSONDecoder().decode(HomeItem.self, from: jsonData)
                    self.page = objc.current_page+1
                    self.totalPage = objc.total
                    let ordersDatas : [OrdersDataItem] = objc.data
                    for order in ordersDatas {
                        self.ordersArray.add(order)
                    }
                    
                    self.MyTableView.reloadData()
                    
                }catch {
                    print(error)
                }
            }
        })
    }
    
    //待办列表
    func requestUnDoneListNew(current_page:Int) -> Void {
        
        //要加密的数据
        let param = ["command":"unDoneList","token":UserTicketModel.sharedInstance.token ?? "","uid":UserTicketModel.sharedInstance.uid ?? "","app_name":"shr","current_page":current_page] as [String : Any]
        let network = NetworkTools.sharedInstance
        network.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"Shipping"], successed: { (resultDict) in
            self.MyTableView.mj_header.endRefreshing()
            if let dict = resultDict["data"] as? NSDictionary{
                let jsonString = network.getJSONStringFromDictionary(dictionary: dict)
                
                guard let jsonData = jsonString.data(using: String.Encoding.utf8) else {return}
                do {
                    let objc: NeedItem = try JSONDecoder().decode(NeedItem.self, from: jsonData)
                    self.page = objc.current_page+1
                    self.totalPage = objc.total
                    self.ordersArray.removeAllObjects()
                    let ordersDatas : [NeedDataItem] = objc.data
                    for order in ordersDatas {
                        self.ordersArray.add(order)
                    }
                    
                    self.MyTableView.reloadData()
                    self.unDoneTotal = self.totalPage
                    //设置标题
                    self.setSegmentedControl()
                    
                }catch {
                    print(error)
                }
                
            }
        })
    }
    
    //待办列表
    func requestUnDoneListMore(current_page:Int) -> Void {
        
        //要加密的数据
        let param = ["command":"unDoneList","token":UserTicketModel.sharedInstance.token ?? "","uid":UserTicketModel.sharedInstance.uid ?? "","app_name":"shr","current_page":current_page] as [String : Any]
        let network = NetworkTools.sharedInstance
        network.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"Shipping"], successed: { (resultDict) in
            self.MyTableView.mj_footer.endRefreshing()
            if let dict = resultDict["data"] as? NSDictionary{
                let jsonString = network.getJSONStringFromDictionary(dictionary: dict)
                
                guard let jsonData = jsonString.data(using: String.Encoding.utf8) else {return}
                do {
                    let objc: NeedItem = try JSONDecoder().decode(NeedItem.self, from: jsonData)
                    self.page = objc.current_page+1
                    self.totalPage = objc.total
                    let ordersDatas : [NeedDataItem] = objc.data
                    for order in ordersDatas {
                        self.ordersArray.add(order)
                    }
                    
                    self.MyTableView.reloadData()
                    
                }catch {
                    print(error)
                }
            }
        })
    }
    
    //捎货人业绩
    func requestAchievement() -> Void {
        
        //要加密的数据
        let param = ["command":"achievement","token":UserTicketModel.sharedInstance.token ?? "","uid":UserTicketModel.sharedInstance.uid ?? "","app_name":"shr"] as [String : Any]
        let network = NetworkTools.sharedInstance
        network.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"Shipping"], successed: { (resultDict) in
            self.MyTableView.mj_header.endRefreshing()
            let data = resultDict["data"] as! [String:AnyObject]
            self.ordersArray.removeAllObjects()
            self.ordersArray.addObjects(from: [["icon_shipper_money","累计捎货收入","￥\(data["total_income"]!)元"],["icon_shipper_complete_order_count","累计完成订单","\(data["total_orders"]!)单"],["icon_shipper_today_complete_order_count","今日完成订单","\(data["today_orders"]!)单"]])
            self.MyTableView.reloadData()
        })
    }
    
    //开关捎货人业务
    func requestChangeTakingStatus(type:String,status:String) -> Void {
        
        //要加密的数据
        let param = ["command":"changeTakingStatus","token":UserTicketModel.sharedInstance.token ?? "","uid":UserTicketModel.sharedInstance.uid ?? "","app_name":"shr","type":type,"status":status] as [String : Any]
        let network = NetworkTools.sharedInstance
        network.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"Shipping"], successed: { (resultDict) in
            
            SwiftProgressHUD.showOnlyText("操作成功")
            if status == "1"{
                self.offDutyButton.isHidden = false
                self.button.isHidden = true
                self.MyTableView.mj_header.beginRefreshing()
            }else {
                self.ordersArray.removeAllObjects()
                self.MyTableView.reloadData()
                self.selIndex = -1
                self.offDutyButton.isHidden = true
                self.button.setTitle("开始接单", for: UIControlState())
                self.button.setTitleColor(UIColor.white, for: UIControlState())
                self.button.backgroundColor = UIColor.orange
                self.button.frame = CGRect(x: 40, y: kScreenHeight*0.5, width: kScreenWitdh-80, height: 40)
                self.button.addTarget(self, action: #selector(self.SELNODutyButton), for: UIControlEvents.touchUpInside)
                self.view.addSubview(self.button)
            }
        })
    }
    
    //接单
    func requestTakeOrder(order_id:String) -> Void {
        
        //要加密的数据
        let param = ["command":"takeOrder","token":UserTicketModel.sharedInstance.token ?? "","uid":UserTicketModel.sharedInstance.uid ?? "","app_name":"shr","order_id":order_id,"lat":UserTicketModel.sharedInstance.lat ?? "","lng":UserTicketModel.sharedInstance.lng ?? ""] as [String : Any]
        let network = NetworkTools.sharedInstance
        network.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"Shipping"], successed: { (resultDict) in
            SwiftProgressHUD.showOnlyText("接单成功")
            self.MyTableView.mj_header.beginRefreshing()

        })
    }
    
    //确认取件
    func requestPickupOrder(order_id:String,indexPath:IndexPath,button:UIButton) -> Void {
        
        //要加密的数据
        let param = ["command":"pickupOrder","token":UserTicketModel.sharedInstance.token ?? "","uid":UserTicketModel.sharedInstance.uid ?? "","app_name":"shr","order_id":order_id,"lat":UserTicketModel.sharedInstance.lat ?? "","lng":UserTicketModel.sharedInstance.lng ?? ""] as [String : Any]
        let network = NetworkTools.sharedInstance
        network.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"Shipping"], successed: { (resultDict) in
            SwiftProgressHUD.showOnlyText("取件成功")
            self.MyTableView.mj_header.beginRefreshing()
        })
    }
    
    //确认送达
    func requestSendtoOrder(order_id:String,indexPath:IndexPath) -> Void {
        
        //要加密的数据
        let param = ["command":"sendtoOrder","token":UserTicketModel.sharedInstance.token ?? "","uid":UserTicketModel.sharedInstance.uid ?? "","app_name":"shr","order_id":order_id,"lat":UserTicketModel.sharedInstance.lat ?? "","lng":UserTicketModel.sharedInstance.lng ?? ""] as [String : Any]
        let network = NetworkTools.sharedInstance
        network.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"Shipping"], successed: { (resultDict) in
            SwiftProgressHUD.showOnlyText("确认送达")
            self.MyTableView.mj_header.beginRefreshing()
        })
    }
    
    //取消订单
    func requestCancelOrder(order_id:String,cancel_reason:String) -> Void {
        
        //要加密的数据
        let param = ["command":"cancelOrder","uid":UserTicketModel.sharedInstance.uid,"token":UserTicketModel.sharedInstance.token,"order_id":order_id,"app_name":"shr","cancel_reason":cancel_reason,"lat":UserTicketModel.sharedInstance.lat ?? "","lng":UserTicketModel.sharedInstance.lng ?? ""]
        NetworkTools.sharedInstance.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"Shipping"], successed: { (resultDict) in

            SwiftProgressHUD.showOnlyText("取消成功")
            self.MyTableView?.mj_header.beginRefreshing()
        })
    }

    /// line
    var toolBarLineView: UIView?
    /**
     设置工具栏
     */
    func setupToolBar() -> Void {
        self.toolBarView = UIView(frame: CGRect(x: 0, y: 44+statusHeight, width: UIScreen.main.bounds.width, height: 40))
        view.addSubview(self.toolBarView!)
        self.toolBarView?.backgroundColor = UIColor(hexString: "F0F0F0")
        
        toolBarLineView = UIView(frame: CGRect(x: 0, y: 39, width: UIScreen.main.bounds.width, height: 1.0/UIScreen.main.scale))
        toolBarLineView?.backgroundColor = UIColor(hexString: "BCBCBC")
        self.toolBarView?.addSubview(toolBarLineView!)
        
        //设置标题
        self.setSegmentedControl()
        //下班按钮
        self.setDutyButton()
    }
    
    /**
     */
    func setSegmentedControl() {
        
        if  segmentedControll != nil {
            segmentedControll.removeFromSuperview()
            segmentedControll = nil
        }

        segmentedControll = HMSegmentedControl(frame: CGRect(x: 20, y: 0, width: 220, height: 39))
        if orderTotal != nil {
            segmentedControll.sectionTitles = ["接单(\(orderTotal!))","待办","业绩"]
            if orderTotal != nil&&unDoneTotal != nil{
               segmentedControll.sectionTitles = ["接单(\(orderTotal!))","待办(\(unDoneTotal!))","业绩"]
            }
        } else {
            segmentedControll.sectionTitles = ["接单","待办","业绩"]
        }
        segmentedControll.backgroundColor = UIColor.clear
        segmentedControll.selectionStyle = HMSegmentedControlSelectionStyleFullWidthStripe
        segmentedControll.titleTextAttributes = [
            NSAttributedStringKey.foregroundColor : UIColor(hexString: "646464"),
            NSAttributedStringKey.font : UIFont.systemFont(ofSize: 12)
        ]
        
        segmentedControll.selectedTitleTextAttributes = [
            NSAttributedStringKey.foregroundColor : UIColor(hexString: "FF7F00"),
            NSAttributedStringKey.font : UIFont.systemFont(ofSize: 12)
        ]
        
        segmentedControll.selectionIndicatorColor =  UIColor(hexString: "FF7F00")
        //UIConstants.NavigationBarTitleStartColor
        segmentedControll.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown

        segmentedControll.selectionIndicatorHeight = 2
        segmentedControll.selectedSegmentIndex = selIndex
        toolBarView?.addSubview(segmentedControll)
        
        segmentedControll.indexChangeBlock = {
            [weak self] (index) in
            if self?.offDutyButton.isHidden == false {
                self?.selIndex = index
                self?.ordersArray.removeAllObjects()
                self?.MyTableView.reloadData()
                self?.MyTableView.mj_header.beginRefreshing()
            }
        }
    }
    
    func setDutyButton() {
        // 下班按钮
        offDutyButton = UIButton(type: UIButtonType.custom)
        offDutyButton.setImage(UIImage(named: "icon_rest"), for: UIControlState())
        offDutyButton.frame = CGRect(x: view.frame.width - 40, y: 2, width: 30, height: 30)
        offDutyButton.titleLabel?.font = UIFont.systemFont(ofSize: 10)
        offDutyButton.setTitleColor(UIColor(hexString: "9C9C9C"), for: UIControlState())
        toolBarView?.addSubview(offDutyButton)
        offDutyButton.addTarget(self, action: #selector(SELOffDutyButton), for: UIControlEvents.touchUpInside)
    }
    
    /**_
     下班事件
    
     - parameter sender:
     */
    @objc func SELOffDutyButton(_ sender: UIButton?) -> Void {
        if unDoneTotal == nil||unDoneTotal>0 {
            SwiftProgressHUD.showOnlyText("请检查待办订单是否全部完成")
            return
        }
         requestChangeTakingStatus(type: "1", status: "2")
    }
    //上班
    @objc func SELNODutyButton(_ sender: UIButton?) -> Void {
        requestChangeTakingStatus(type: "1", status: "1")
    }
    
    //接单
    @objc func SELrecvOrderButton(_ sender: UIButton?) -> Void {
        let cell = sender?.superview?.superview?.superview as! ReceiveOrderCell
        let indexPath : IndexPath = MyTableView.indexPath(for: cell)!
        let orderItem = ordersArray[indexPath.row] as! OrdersDataItem
        requestTakeOrder(order_id: orderItem.order_id)
    }
    
    //确认送达
    @objc func SELconfirmButton(_ sender: UIButton?) -> Void {
        let cell = sender?.superview?.superview?.superview as! NeedDealtCell
        let indexPath : IndexPath = MyTableView.indexPath(for: cell)!
        let needItem = ordersArray[indexPath.row] as! NeedDataItem
        if sender?.titleLabel?.text == "确认送达" {
            requestSendtoOrder(order_id: needItem.order_id,indexPath: indexPath)
        }else {//确认取件
            requestPickupOrder(order_id: needItem.order_id,indexPath: indexPath,button: sender!)
        }
        
    }
    
    //取消接单
    @objc func SELcancelButton(_ sender: UIButton?) -> Void {
        let cell = sender?.superview?.superview?.superview as! NeedDealtCell
        let indexPath : IndexPath = MyTableView.indexPath(for: cell)!
        let needItem = ordersArray[indexPath.row] as! NeedDataItem
        let alertController = UIAlertController(title: "取消原因",
                                                message: nil, preferredStyle: .alert)
        alertController.addTextField {
            (textField: UITextField!) -> Void in
            textField.placeholder = "输入取消原因"
        }
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        let okAction = UIAlertAction(title: "确认", style: .default, handler: {
            action in
            //也可以用下标的形式获取textField let login = alertController.textFields![0]
            let firstTextField = alertController.textFields!.first!
            self.requestCancelOrder(order_id: needItem.order_id, cancel_reason: firstTextField.text!)
        })
        alertController.addAction(cancelAction)
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
}

extension ReceiveOrderViewController : UITableViewDataSource,UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.ordersArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if selIndex == 0{
            let cell = tableView.dequeueReusableCell(withIdentifier: receiveOrderCell) as! ReceiveOrderCell
            cell.ordersItem = self.ordersArray[indexPath.row] as? OrdersDataItem
            cell.selectionStyle = .none
            cell.recvOrderButton.addTarget(self, action: #selector(SELrecvOrderButton), for: UIControlEvents.touchUpInside)
            return cell
        }else if selIndex == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: needDealtCell) as! NeedDealtCell
            cell.needItem = self.ordersArray[indexPath.row] as? NeedDataItem
            cell.selectionStyle = .none
            cell.confirmButton.addTarget(self, action: #selector(SELconfirmButton), for: UIControlEvents.touchUpInside)
            cell.cancelButton.addTarget(self, action: #selector(SELcancelButton), for: UIControlEvents.touchUpInside)
            return cell
        }
        let cell = UITableViewCell(style: .value1, reuseIdentifier: tableViewCell)
        cell.selectionStyle = .none
        let array = self.ordersArray[indexPath.row] as! [String]
        if array.count==3 {
            cell.imageView?.image = UIImage(named: array[0])
            cell.textLabel?.text = array[1]
            cell.detailTextLabel?.text = "\(array[2])"
            cell.detailTextLabel?.textColor = UIColor(hexString: "FF7F00")
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if selIndex==2 {
            if indexPath.row==1{
            let orderVc = OrderViewController()
                orderVc.type = "1"
                orderVc.title = "累计完成订单"
            navigationController?.pushViewController(orderVc, animated: true)
            }else if indexPath.row==2 {
            let orderVc = OrderViewController()
            orderVc.type = "2"
            orderVc.title = "今日完成订单"
            navigationController?.pushViewController(orderVc, animated: true)
            }
        }
    }
}
